package cn.bdqn.controller;
import cn.bdqn.code.Captcha;
import cn.bdqn.code.GifCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class VerifyCodeController {
    @RequestMapping("/captcha")
    public void CreateCaptchaServlet(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.setHeader("Pragma", "No-cache");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setDateHeader("Expires", 0);
            //返回一张图片
            resp.setContentType("image/jpg");
            //创建验证码
            Captcha captcha = new GifCaptcha(106, 35, 4);
            //发送到页面
            captcha.out(resp.getOutputStream());
            //存入Session
            req.getSession().setAttribute("_code", captcha.text().toLowerCase());
        } catch (Exception e) {
//            System.out.println("验证码获取成功！");
        }
    }

    @RequestMapping("/verifyCaptcha")
    public void VerifyCaptchaServlet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String vercode = req.getParameter("vercode");
        //得到Session
        boolean code = vercode.toLowerCase().equals(req.getSession().getAttribute("_code"));
        //返回验证结果
        resp.getWriter().println(code);
    }
}
